package homework.ch11_13.p4;

import java.util.ArrayList;
import java.util.List;

public class CompositeIterator implements Iterator {

   protected List<Iterator> iterators=new ArrayList<>();

    public CompositeIterator(Iterator iterator) {
        iterators.add(iterator);
    }

    public boolean hasNext(){
        if(iterators.size()>0){
            Iterator it=iterators.get(0);
            if(!(it.hasNext())){
                iterators.remove(0);
                return hasNext();
            }
            else
                return true;
        }

        else
            return false;
    }

   /* public Component next(){
       if(hasNext()){
           Component c=(Component)iterators.get(0);
           System.out.println("id: "+c.getId()+", name:"+c.getName()+", price:"+c.getPrice());
           if(c instanceof CompositeComponent){
               int i=0;

               System.out.println("\nsub-components of "+((Component) iterators.get(0)).getName()+":\n");
           }
           iterators.remove(0);
           return c;
       }
       else return null;
    }
}
*/
   @Override
   public Component next() {
       if(hasNext()){
           //取出队列里的第一个迭代器
           Iterator it = iterators.get(0);
           //从这个迭代器取出下一个组件
           Component c = it.next();
           iterators.add(c.iterator());
           return c;
       }
       else{
           return null;
       }
   }
}
